﻿using Abp.EntityFrameworkCore;
using HCD.Configuration;
using HCD.Web;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;

namespace HCD.EntityFrameworkCore
{
    /// <summary>
    /// EF Core PMC commands 基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class DbContextFactory<T> : IDesignTimeDbContextFactory<T> where T : AbpDbContext
    {
        /// <summary>
        /// 要采用的数据库连接节点名称
        /// </summary>
        public abstract string ConnectionStringName { get; }
        /// <summary>
        /// 创建DbContext实例
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public abstract T CreateDbContext(DbContextOptions<T> options);
        public T CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<T>();
            var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder(), args?.Length > 0 ? args[0] : null);
            DbContextOptionsConfigurer.Configure(
                builder,
                configuration.GetConnectionString(ConnectionStringName)
            );
            return CreateDbContext(builder.Options);
        }
    }
}